/**
 * 
 */
package com.geezdata.cps.ttk.core.command;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.geezdata.cps.base.response.BaseResponse;
import com.geezdata.cps.cqrs.command.Command;
import com.geezdata.cps.ttk.common.request.CreateOrUpdatePromotionSpaceRequest;
import com.geezdata.cps.ttk.common.response.CreateOrUpdatePromotionSpaceResult;
import com.geezdata.cps.ttk.domain.domain.PromotionSpace;
import com.geezdata.cps.ttk.domain.factory.PromotionSpaceFactory;
import com.geezdata.cps.ttk.mapper.mapper.PromotionSpaceMapper;

/**
 * @author tfwan
 * @date 创建时间：2018年6月12日 下午3:45:16
 *
 */
@Service
public class CreateOrUpdatePromotionSpaceCommand implements Command<CreateOrUpdatePromotionSpaceRequest, CreateOrUpdatePromotionSpaceResult> {
	@Autowired
	private PromotionSpaceMapper promotionSpaceMapper;
	@Override
	@Transactional
	public BaseResponse<CreateOrUpdatePromotionSpaceResult> execute(CreateOrUpdatePromotionSpaceRequest request) {
		CreateOrUpdatePromotionSpaceResult result = new CreateOrUpdatePromotionSpaceResult();
		
		PromotionSpace exsitsPromotionSpace = testIfExistPromotionSpace(request);
		PromotionSpace promotionSpace = PromotionSpaceFactory.newInstance(request, exsitsPromotionSpace);
		createOrUpdatePromotionSpace(exsitsPromotionSpace, promotionSpace);
        result.setPromotionSpaceId(promotionSpace.getPromotionSpaceId());
		return BaseResponse.success(result);
	}
	
	private void createOrUpdatePromotionSpace(PromotionSpace exsitsPromotionSpace, PromotionSpace promotionSpace) {
		if(exsitsPromotionSpace == null) {
			promotionSpaceMapper.insert(promotionSpace);
		} else {
			promotionSpaceMapper.updateByPrimaryKey(promotionSpace);
		}
	}

	private PromotionSpace testIfExistPromotionSpace(CreateOrUpdatePromotionSpaceRequest request) {
		PromotionSpace exsitsPromotionSpace = null;
		if(request.getPromotionSpaceReqVO().getPromotionSpaceId() != null) {
			exsitsPromotionSpace = promotionSpaceMapper.selectByPrimaryKey(request.getPromotionSpaceReqVO().getPromotionSpaceId());
		}
		return exsitsPromotionSpace;
	}
}
